package program;

import java.io.*;
import lexer.*;
import parser.*;
import libraries.EasyIn;
import codeGeneration.*;

public class Program {

	public static void main(String[] args) {
		
		String fileName, outputFile;
		// If we run it from console, we don't want this input
		if(args.length >= 2)
		{
			fileName = args[0];
			outputFile = args[1];
		}
		else
		{
			// Get the names of the files we would like to interact with
			System.out.println("Enter the filename of the LOGO script input: (eg triangle.t)");
			fileName = EasyIn.getString();

			System.out.println("Enter the filename for the output: (eg output1.ps)");
			outputFile = EasyIn.getString();
		}
		

		// Convert file into Token Stream/Array
		Lexer lexer = new Lexer(fileName);
		Token[] lexerOutput = lexer.lexFile();

		LogoProgram program = null;

		try {
			// Parse tokens into a LogoProgram object, which is the first node in a Tree
			program = LogoParser.parseTokens(lexerOutput);
		} catch (LogoParseException e) {
			// Encountered an error parsing tokens
			System.out.println("Exception parsing tokens: " + e.getMessage());
			// non-zero exit code on error
			System.exit(1);
		}

		File file = new File(outputFile);
		PrintWriter out = null;
		try {
			out = new PrintWriter(file);
		} catch (FileNotFoundException e) {
			// Unable to write to file
			System.out.println("Fatal Error: Unable to open " + e.getMessage() + " for writing.");
			System.exit(2);
		}

		CodeGenerator cg = new CodeGenerator(out);
		try {
			// Do more checks then Generate PostScript from the LogoProgram passed in
			cg.generateCode(program);
		} catch (CodeGenerationException e) {
			System.out.println(e.getMessage());
			System.exit(3);
		}
		// Flush stream.. a bit redundant but nevermind
		out.flush();

		System.out.println("Successfully Compiled " + fileName + " to " + outputFile);
	}
}
